//
//  SetUpCenterTableViewController.m
//  WWXELuShang
//
//  Created by lanou on 15/12/26.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "SetUpCenterTableViewController.h"

@interface SetUpCenterTableViewController ()

@property (nonatomic, strong)UIAlertController *alert;

@end

@implementation SetUpCenterTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kBackGroundColor;
    self.navigationController.navigationBar.barTintColor = kBarColor;
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return 3;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier ];
    
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
        
    }
    if (indexPath.row == 0) {
        UISwitch *switchButton = [[UISwitch alloc] initWithFrame:CGRectMake(kWidth - kWidth / 40 - kWidth / 8, cell.frame.size.height / 4, kWidth / 15, cell.frame.size.height / 2)];
        switchButton.on = YES;
        [switchButton addTarget:self action:@selector(changeSwitch:) forControlEvents:(UIControlEventValueChanged)];
         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        if ([[defaults valueForKey:@"Local"] isEqualToString:@"NO"]) {
            switchButton.on = NO;
        }
        [cell.contentView addSubview:switchButton];
    }
    
    NSArray *array = @[@"闹钟提醒",@"清除缓存",@"检测更新"];
    cell.textLabel.text = array[indexPath.row];
    cell.textLabel.textColor = [UIColor darkGrayColor];
    cell.backgroundColor = kBackGroundColor;
    // Configure the cell...
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 1) {
        NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *imagePath = [cachePath stringByAppendingString:@"/lanou3g.com.WWXELuShan/fsCachedData"];
        NSString *webPath = [cachePath stringByAppendingString:@"/lanou3g.com.WWXELuShan/WebKit"];
        CGFloat number1 = [self folderSizeAtPath:imagePath];
        CGFloat number2 = [self folderSizeAtPath:webPath];
        CGFloat number = number1 + number2;
        NSString *size = [NSString stringWithFormat:@"是否清除缓存:%.2fMB",number];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:size preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [self deleteWithPath:imagePath];
            [self deleteWithPath:webPath];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:nil];
        [alert addAction:cancelAction];
        [alert addAction:sureAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
    if (indexPath.row == 2) {
        self.alert = [UIAlertController alertControllerWithTitle:nil message:@"正在检测更新..." preferredStyle:(UIAlertControllerStyleAlert)];
        [self presentViewController:_alert animated:YES completion:nil];
        [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(timeAlert) userInfo:nil repeats:NO];
    }
    
}

- (void)timeAlert {

    self.alert.message = @"已经是最新版本 \n v1.0.0";
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(missAlert) userInfo:nil repeats:NO];
}

- (void)missAlert {
    [self.alert dismissViewControllerAnimated:YES completion:nil];
}

- (void)changeSwitch:(UISwitch *)switchButton {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (switchButton.on == NO) {
        [defaults setObject:@"NO" forKey:@"Local"];
    }else {
        [defaults setObject:@"YES" forKey:@"Local"];
    }
    
}

//单个文件的大小
- (long long)fileSizeAtPath:(NSString *)filePath {
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]) {
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
//遍历文件夹获得文件夹大小返回多少M
- (CGFloat)folderSizeAtPath:(NSString *)folderPath {
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]){
        return 0;
    }
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    long long folderSize = 0;
    NSString *fileName;
    while ((fileName = [childFilesEnumerator nextObject]) != nil) {
        NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize / (1024.0 * 1024.0);
}

//遍历文件夹删除文件
- (void)deleteWithPath:(NSString *)path{
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:path]) {
        return;
    }
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:path] objectEnumerator];
    NSString *fileName;
    while ((fileName = [childFilesEnumerator nextObject]) != nil) {
        NSString *fileAbsolutePath = [path stringByAppendingPathComponent:fileName];
        [manager removeItemAtPath:fileAbsolutePath error:nil];
    }

}



/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
